package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.BaseException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;


@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;
    /*
    * 提交订单（用户下单）
    * 订单的详情商品在用户购购物车里面，这个太坑了，我开始都没想到
    * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        //处理业务异常(购物车为空、地址为空)
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByUserId(userId);
        if(shoppingCarts == null || shoppingCarts.isEmpty()){
            //购物车为空
            throw new BaseException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            //地址薄为空
            throw new BaseException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //补全订单数据，因为前端传递的只是部分数据，我们要利用购物车表、地址表、用户表的数据补全订单数据
        //生成订单号
        String timePart = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        String randomPart = String.format("%04d", new Random().nextInt(10000)); // 4位随机数
        String number = timePart + randomPart; // 总长度为21位
        //生成详细订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);

        orders.setNumber(number);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        //用户名，因为没有权限获取wx号的用户名，只能用收货人姓名
        orders.setUserName(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //向订单表插入一条数据，表示一个订单
        orderMapper.insert(orders);
        //向订单明细表插入n条数据，表示订单的n个商品
        //订单id
        Long orderId = orders.getId();
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(shoppingCart -> {
            OrderDetail orderDetail = OrderDetail.builder()
                    .name(shoppingCart.getName())
                    .image(shoppingCart.getImage())
                    .orderId(orderId)
                    .dishId(shoppingCart.getDishId())
                    .setmealId(shoppingCart.getSetmealId())
                    .dishFlavor(shoppingCart.getDishFlavor())
                    .number(shoppingCart.getNumber())
                    .amount(shoppingCart.getAmount()).build();
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailMapper.insertBatch(orderDetails);

        //清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //构建返回给前端的OrderSubmitVO对象
        OrderSubmitVO res = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(number)
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return res;
    }


    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID) //支付状态，已支付
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        //通过websocket向前端发送消息，提示商家接单
        //拼凑消息
        Map<String, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber()+" 已支付,请尽快接单");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    /*
    * 查询订单详情
    * @param id 订单id
    * */
    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        orderVO.setOrderDishes("sb fuck you!");
        return orderVO;
    }

    /*
    * 用户取消订单
    * */
    @Override
    public void cancel(Long id){
        //只需要根据id修改订单状态和订单取消时间即可
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    /*
    * 订单分页查询
    * */
    @Override
    public PageResult page(Integer page, Integer pageSize, Integer status){
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        Page<OrderVO> pageResult = (Page<OrderVO>) orderMapper.pageQuery(ordersPageQueryDTO);
        return new PageResult(pageResult.getTotal(),pageResult.getResult());
    }

    /*
    * 用户催单
    * */
    @Override
    public void reminder(Long id){
        //判断订单id是否合法
        Orders order = orderMapper.getById(id);
        if(order == null){
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }
        //通过websocket向前端发送消息，提示用户催单
        Map<String,Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",order.getId());
        map.put("content","订单号："+order.getNumber()+" 用户催单了");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    /*
    * 商家接单
    * */
    @Override
    public void accept(Long orderId){
        Orders orders = orderMapper.getById(orderId);
        if(orders == null){
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus() != Orders.TO_BE_CONFIRMED){
            throw new BaseException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /*
    * 商家派送订单
    * */
    @Override
    public void delivery(Long orderId){
        Orders orders = orderMapper.getById(orderId);
        if(orders == null){
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus() != Orders.CONFIRMED){
            throw new BaseException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /*
    * 商家取消订单
    * */
    @Override
    public void cancelByBusiness(OrdersCancelDTO ordersCancelDTO){
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if(orders == null){
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /*
    * 商家拒绝订单
    * */
    @Override
    public void rejectionByBusiness(OrdersRejectionDTO ordersRejectionDTO){
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        if(orders == null){
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /*
    * 商家完成订单
    * */
    @Override
    public void complete(Long id){
        Orders orders = orderMapper.getById(id);
        if(orders == null){
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(orders.getStatus() != Orders.DELIVERY_IN_PROGRESS){
            throw new BaseException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /*
    * 统计各个状态订单的数量
    * */
    @Override
    public OrderStatisticsVO statistics(){
        //待接单数量
        Integer toBeConfirmed = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        //待派送数量
        Integer confirmed = orderMapper.countByStatus(Orders.CONFIRMED);
        //派送中数量
        Integer deliveryInProgress = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);

        return  OrderStatisticsVO
                .builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
    }

    /*
    *
    * 商家端订单分页查询
    * */
    @Override
    public PageResult pageByAdmin(OrdersPageQueryDTO ordersPageQueryDTO){
        Integer page = ordersPageQueryDTO.getPage();
        Integer pageSize = ordersPageQueryDTO.getPageSize();
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        PageHelper.startPage(page,pageSize);
        List<OrderVO> pageResult =orderMapper.pageQuery(ordersPageQueryDTO);
        //为每条订单设置字符串形式的菜品信息
        for(OrderVO orderVO : pageResult){
            List<OrderDetail> orderDetailList = orderVO.getOrderDetailList();
            List<String> temp = orderDetailList.stream().map(OrderDetail::getName).collect(Collectors.toList());
            orderVO.setOrderDishes(String.join(",",temp));
        }
        Page<OrderVO> endPageResult = (Page<OrderVO>) pageResult;

        return new PageResult(endPageResult.getTotal(),endPageResult.getResult());
    }

    /**
     * 订单支付
     * @param
     * @return
     */
/*    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        LocalDateTime check_out_time = LocalDateTime.now();//更新支付时间
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time,ordersPaymentDTO.getOrderNumber());
        return vo;
    }*/

    /*
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
}
